﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;

using DotNetNuke.Common;
using DotNetNuke.Common.Lists;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.WebControls;

namespace DotNetNuke.Modules.UserDefinedTable
{

  /// <summary>
  /// Editor for Module Templates
  /// </summary>
  public partial class TemplateList : PortalModuleBase, IActionable, IPostBackEventHandler
  {

    private List<TemplateValueInfo> Customizations;

    public TemplateList()
    {
      //base.Load += new EventHandler(this.Page_Load);
      this.Customizations = new List<TemplateValueInfo>();
    }



    protected override void OnInit(EventArgs e)
    {
      base.OnInit(e);
      //base.Load += new EventHandler(this.Page_Load);

      cmdApply.Click += new EventHandler(cmdApply_Click);
      GridView1.SelectedIndexChanged += new EventHandler(GridView1_SelectedIndexChanged);
    }



    //protected void Page_Load(object sender, EventArgs evt)
    protected override void OnLoad(EventArgs evt)
    {
      base.OnLoad(evt);

      this.Description.Text = string.Format(Localization.GetString("ChooseTemplateOrManage.Text", LocalResourceFile), ModuleContext.EditUrl("Manage"));

      if (!this.IsPostBack)
      {
        GridView gridView = this.GridView1;
        DotNetNuke.Services.Localization.Localization.LocalizeGridView(ref gridView, this.LocalResourceFile);
        this.GridView1 = gridView;
      }
      this.BindData();

      if (this.GridView1.Rows.Count == 0)
        this.litTemplates.Text = DotNetNuke.Services.Localization.Localization.GetString("NoTemplates", this.LocalResourceFile);
      
    }





    private void BindData()
    {
      if (this.GridView1.SelectedRow != null)
      {
        this.LoadCustomization();
        this.TemplateCustomValuesEditor.DataSource = this.Customizations;
        this.TemplateCustomValuesEditor.DataBind();
      }
    }




    protected void cmdApply_Click(object sender, EventArgs evt)
    {
      XmlDocument content = null;
      foreach (TemplateValueInfo info in this.Customizations)
      {
        if ( !string.IsNullOrEmpty(info.ValueSource) )
        {
          ((XmlElement)info.Node.ParentNode).SetAttribute(info.ValueSource, info.Value);
          ((XmlElement)info.Node.ParentNode).SetAttribute("installmode", "force");
        }
        else
          info.Node.ParentNode.InnerText = info.Value;
        
        content = info.Node.OwnerDocument;
      }
      TemplateController.LoadTemplate(content, this.ModuleContext.PortalId, this.ModuleContext.TabId);
      this.DeleteMe();
    }




    private void DeleteMe()
    {
      ModuleController controller = new ModuleController();
      controller.DeleteTabModule(this.ModuleContext.TabId, this.ModuleContext.ModuleId, false);
      controller.DeleteModule(this.ModuleContext.ModuleId);
      this.Response.Redirect(Globals.NavigateURL(this.ModuleContext.TabId), true);
    }




    protected void GridView1_SelectedIndexChanged(object sender, EventArgs evt)
    {
      this.BindData();
      if (this.Customizations.Count > 0)
      {
        this.GridView1.Visible = false;
        this.Description.Text = string.Format(DotNetNuke.Services.Localization.Localization.GetString("CustomizeTemplate", this.LocalResourceFile), this.GridView1.SelectedRow.Cells[1].Text, this.GridView1.SelectedRow.Cells[2].Text);
        this.cmdApply.Visible = true;
      }
      else
      {
        TemplateController.LoadTemplate(HttpUtility.HtmlDecode(this.GridView1.SelectedRow.Cells[1].Text), this.ModuleContext.PortalId, this.ModuleContext.TabId);
        this.DeleteMe();
      }
    }




    private void LoadCustomization()
    {
      XmlDocument document = new XmlDocument();
      document.LoadXml(TemplateController.Templates[HttpUtility.HtmlDecode(this.GridView1.SelectedRow.Cells[1].Text)].ExportContent);
      ListController controller = new ListController();
      XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);
      nsmgr.AddNamespace("ask", "DotNetNuke/ModuleTemplate");

      string attribute, str3, str2, str;
      int num2, entryID;
      TemplateValueInfo item;

      foreach(XmlElement current in document.SelectNodes("//ask:user", nsmgr))
      {
        attribute = current.GetAttribute("valuesource");
        str3 = string.Empty;

        if ( !string.IsNullOrEmpty(attribute) )
          str3 = ((XmlElement)current.ParentNode).GetAttribute(attribute);
        
        else
          str3 = current.ParentNode.InnerText.Trim();
        
        str2 = Utilities.CStrN(current.GetAttribute("editor"), "Text");
        num2 = int.Parse(Utilities.CStrN(current.GetAttribute("length"), "255"));
        entryID = controller.GetListEntryInfo("DataType", str2).EntryID;
        str = Utilities.CStrN(current.GetAttribute("caption"), Utilities.CStrN(attribute, current.ParentNode.Name));
        item = new TemplateValueInfo();
        item.Caption = str;
        item.Editor = entryID;
        item.Node = current;
        item.Value = str3;
        item.ValueSource = attribute;
        item.Length = num2;
        this.Customizations.Add(item);
      }
    }





    public void RaisePostBackEvent(string eventArgument)
    {
      if (eventArgument == "Rescan")
      {
        TemplateController.ClearCache();
        this.Response.Redirect(Globals.NavigateURL(this.ModuleContext.TabId), true);
      }
    }




    ModuleActionCollection DotNetNuke.Entities.Modules.IActionable.ModuleActions
    {
      get
      {
        ModuleActionCollection actions = new ModuleActionCollection();
        try
        {
          actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("Rescan", this.LocalResourceFile), "", "", this.ResolveUrl("~/images/action_refresh.gif"), string.Format("javascript:{0}", this.Page.ClientScript.GetPostBackEventReference(this, "Rescan")), false, SecurityAccessLevel.Edit, true, false);
        }
        catch (Exception e)
        {

          Exception exc = e;
          DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);

        }
        return actions;
      }
    }





    public ModuleActionCollection ModuleActions
    {
      get
      {
        ModuleActionCollection actions = new ModuleActionCollection();
        try
        {
          actions.Add(this.ModuleContext.GetNextActionID(), DotNetNuke.Services.Localization.Localization.GetString("Rescan", this.LocalResourceFile), "", "", this.ResolveUrl("~/images/action_refresh.gif"), string.Format("javascript:{0}", this.Page.ClientScript.GetPostBackEventReference(this, "Rescan")), false, SecurityAccessLevel.Edit, true, false);
        }
        catch (Exception e)
        {

          Exception exc = e;
          DotNetNuke.Services.Exceptions.Exceptions.LogException(exc);

        }
        return actions;
      }
    }

  }

}

